package controllers

import (
	comm "com.wangzhumo.lottery/common"
	"com.wangzhumo.lottery/conf"
	"com.wangzhumo.lottery/models"
	"com.wangzhumo.lottery/services"
	"com.wangzhumo.lottery/utils"
	"fmt"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
	"strings"
)

type AdminCodeController struct {
	Ctx            iris.Context
	ServiceUser    services.UserService
	ServiceIp      services.BlackIpService
	GiftServices   services.GiftServices
	CodeService    services.CodeService
	UserDayService services.UserDayService
	ResultService  services.ResultService
}

// Get 首页
func (c *AdminCodeController) Get() mvc.Result {
	giftId := c.Ctx.URLParamIntDefault("gift_id", 0)
	page := c.Ctx.URLParamIntDefault("page", 1)
	size := 100
	pagePrev := ""
	pageNext := ""

	// 数据
	var dataList []models.LtCoupon
	var total int
	var codeNum int
	var cacheNum int

	if giftId > 0  {
		dataList = c.CodeService.Search(giftId)
		// 对比缓存数据
		codeNum, cacheNum = utils.GetCacheCodesNum(giftId, c.CodeService)
	}else{
		dataList, _ = c.CodeService.GetAll(page, size)
	}
	total = (page - 1) + len(dataList)

	if len(dataList) >= size {
		if giftId > 0 {
			total = int(c.CodeService.CountByGift(giftId))
		}else {
			total = int(c.CodeService.CountAll())
		}
		pageNext = fmt.Sprintf("%d",page+1)
	}

	// 根据页数
	if page > 1 {
		pagePrev = fmt.Sprintf("%d", page-1)
	}
	return mvc.View{
		Name: "admin/code.html",
		Data: iris.Map{
			"Title":    "优惠券管理后台",
			"Channel":  "code",
			"GiftId" : giftId,
			"Datalist": dataList,
			"Total":    total,
			"PageNext": pageNext,
			"PagePrev": pagePrev,
			"CodeNum":  codeNum,
			"CacheNum": cacheNum,
		},
		Layout: "admin/layout.html",
	}
}

// PostImport 增加优惠券
func (c *AdminCodeController) PostImport()  {
	giftId := c.Ctx.URLParamIntDefault("gift_id", 0)
	if giftId < 1 {
		c.Ctx.Text("需要指定GiftID，<a href='' onclick='history.go(-1);return false;'>返回</a>")
		return
	}

	// 否则插入
	gift, _ := c.GiftServices.Get(giftId,false)
	if gift == nil || gift.Id < 1 || gift.Gtype != conf.GtypeCodeDiff {
		c.Ctx.Text("当前优惠券不支持导入，<a href='' onclick='history.go(-1);return false;'>返回</a>")
		return
	}

	codes := c.Ctx.PostValue("codes")
	now:= comm.NowUnix()
	list := strings.Split(codes,"\n")
	// 成功
	succeedNum := 0
	// 失败
	failNum := 0
	for _, s := range list {
		code := strings.TrimSpace(s)
		if code != "" {
			// 可以加入
			codeData := &models.LtCoupon{
				GiftId: giftId,
				Code: code,
				SysCreated: now,
			}
			err := c.CodeService.Insert(codeData)
			if err != nil {
				failNum++
			}else{
				importOk := utils.ImportCacheCodes(giftId, code)
				if importOk {
					succeedNum++
				}else{
					failNum++
				}
			}
		}
	}
	c.Ctx.HTML(fmt.Sprintf("成功导入 %d 条，导入失败 %d 条，<a href='/admin/code?gift_id=%d'>返回</a>", succeedNum, failNum, giftId))
}


// GetDelete 删除礼物 - 更新为1
func (c *AdminCodeController) GetDelete() mvc.Result {
	giftId, err := c.Ctx.URLParamInt("id")

	// 获取到id，直接移除 sys_status = 1
	if err == nil {
		c.GiftServices.Delete(giftId)
	}

	return mvc.Response{
		Path: "/admin/gift",
	}
}

// GetReset 恢复礼物 - 更新为0
func (c *AdminCodeController) GetReset() mvc.Result {
	giftId, err := c.Ctx.URLParamInt("id") // 获取到id，直接移除
	if err == nil {
		c.GiftServices.Update(&models.LtGift{
			Id:        giftId,
			SysStatus: 0},
			[]string{"sys_status"},
		)
	}
	return mvc.Response{
		Path: "/admin/gift",
	}
}

// GetRecache  重新导入
func (c *AdminCodeController) GetRecache()  {
	// 返回
	refer := c.Ctx.GetHeader("Referer")
	if refer == "" {
		refer  = "/admin/code"
	}

	// 获取参数
	giftId,err := c.Ctx.URLParamInt("id")
	if giftId < 1 || err != nil {
		c.Ctx.HTML(fmt.Sprintf("需要指定GiftID，<a href='%s'>返回</a>",refer))
		return
	}

	// 否则执行
	succeedNum, failNum := utils.ReCacheCodes(giftId, c.CodeService)
	c.Ctx.HTML(fmt.Sprintf("成功导入 %d 条，导入失败 %d 条，<a href='%s'>返回</a>", succeedNum, failNum,refer))
}
